<!-- 用户管理 -->
<template>
  <div class="app-container">
    <!-- 用户列表 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input v-model="queryParams.keywords" placeholder="用户名/昵称/手机号" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="全部" clearable class="!w-[200px]">
            <el-option label="全部" :value="0" />
            <el-option label="显示" :value="1" />
            <el-option label="隐藏" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker :editable="false" class="!w-[240px]" v-model="queryParams.createTime" type="daterange"
            range-separator="~" value-format="x" start-placeholder="开始时间" end-placeholder="截止时间" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <div class="flex-x-between">
          <div>
            <el-button v-hasPerm="['notice/add']" type="success" @click="handleOpenDialog()">
              <i-ep-plus />
              新增
            </el-button>
            <el-button v-hasPerm="['notice/del']" type="danger" :disabled="removeIds.length === 0"
              @click="handleDelete()">
              <i-ep-delete />
              删除
            </el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="pageData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column key="id" label="编号" align="center" prop="id" width="80" />
        <el-table-column label="标题" align="center" prop="title" />
        <el-table-column label="标头" align="center" prop="had" />
        <el-table-column label="简介" align="center" prop="describe" />
        <el-table-column label="状态" align="center" prop="is_show" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.is_show == 0 ? 'success' : 'info'">
              {{ scope.row.is_show == 0 ? "显示" : "隐藏" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="180">
          <template #default="scope">
            <template v-if="scope.row.created_at > 0">
              {{ formatTimestamp(scope.row.created_at * 1000) }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="scope">
            <el-button v-hasPerm="['notice/edit']" type="primary" link size="small"
              @click="handleOpenDialog(scope.row.id)">
              <i-ep-edit />
              编辑
            </el-button>
            <el-button v-hasPerm="['notice/del']" type="danger" link size="small" @click="handleDelete(scope.row.id)">
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
    </el-card>

    <!-- 用户表单弹窗 -->
    <el-drawer v-model="dialog.visible" size="50%" :title="dialog.title" append-to-body @close="handleCloseDialog">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="标头" prop="had">
          <el-input v-model="formData.had" placeholder="请输入标头" />
        </el-form-item>
        <el-form-item label="图片" prop="images">
          <image-upload v-if="dialog.visible" v-model="formData.images" />
        </el-form-item>
        <el-form-item label="简介" prop="describe">
          <el-input v-model="formData.describe" placeholder="请输入简介简介" />
        </el-form-item>
        <el-form-item label="是否上线" prop="is_show">
          <el-switch v-model="formData.is_show" inline-prompt active-text="是" inactive-text="否" :active-value="0"
            :inactive-value="1" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <editor v-model="formData.content" style="height: calc(100vh - 180px)" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "User",
  inheritAttrs: false,
});

import NoticeAPI, { NoticeForm, UserPageQuery, UserPageVO } from "@/api/notice";
import ImageUpload from "@/components/Upload/ImageUpload.vue";
import Editor from "@/components/WangEditor/index.vue";
import { formatTimestamp } from '@/utils/index'

const queryFormRef = ref(ElForm);
const formRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);
const pageData = ref<UserPageVO[]>();
/** 部门下拉选项 */
const deptOptions = ref<OptionType[]>();
/** 角色下拉选项 */
const roleOptions = ref<OptionType[]>();
/** 用户查询参数  */
const queryParams = reactive<UserPageQuery>({
  pageNum: 1,
  pageSize: 10,
  createTime: []
});

/**  用户弹窗对象  */
const dialog = reactive({
  visible: false,
  title: "",
});

/** 导入弹窗显示状态 */
const importDialogVisible = ref(false);

// 用户表单数据
const formData = reactive<NoticeForm>({
  status: 1,
  images: []
});

/** 用户表单校验规则  */
const rules = reactive({
  name: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  code: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  if (queryParams.createTime.length > 0) {
    queryParams.startDate = queryParams.createTime[0] / 1000;
    queryParams.endDate = queryParams.createTime[1] / 1000;
  }
  NoticeAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.createTime = [];
  queryParams.startDate = 0;
  queryParams.endDate = 0;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}


/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(id?: number) {
  dialog.visible = true;

  if (id) {
    dialog.title = "修改公屏";
    NoticeAPI.getFormData({ id }).then((data) => {
      if (data.notice.image != "") {
        data.notice.images = data.notice.image.split(",");
      } else {
        data.notice.images = []
      }

      Object.assign(formData, data.notice);
    });
  } else {
    dialog.title = "新增公屏";
  }
}

/** 关闭弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  formRef.value.resetFields();
  formRef.value.clearValidate();

  formData.content = '';
  formData.id = undefined;
  formData.status = 1;
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  formRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.id;
      formData.image = formData.images.join(",");
      loading.value = true;
      if (userId) {
        NoticeAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        NoticeAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = id ? [id] : removeIds.value;

  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      NoticeAPI.deleteByIds({ ids: userIds })
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}


onMounted(() => {
  handleQuery();
});
</script>
